package com.rankeiot.platform.controller;

import com.rankeiot.core.Config;
import com.rankeiot.core.anno.Auth;
import com.rankeiot.core.config.ConfigItemMeta;
import com.rankeiot.core.config.ConfigManager;
import com.rankeiot.core.data.response.Resp;
import com.rankeiot.core.event.ConfigChangeEvent;
import com.rankeiot.core.util.LocaleUtil;
import com.rankeiot.platform.PlatformMenu;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 配置管理
 */
@Auth(PlatformMenu.CONFIG)
@RestController
@RequestMapping("configs")
@RequiredArgsConstructor
public class ConfigsController {
    final ApplicationContext context;
    @GetMapping ("meta")
    public Resp meta(){
        Map<String, List<ConfigItemMeta>> metas=ConfigManager.getMetas();
        Map<String,List<ConfigItemMeta>> codeMetas=new HashMap<>();
        Locale locale=LocaleUtil.getLocale();
        for(Map.Entry<String,List<ConfigItemMeta>> entry:metas.entrySet()){
            codeMetas.put(LocaleUtil.d(entry.getKey(),locale),entry.getValue());
        }
        return Resp.of(codeMetas);
    }
    @GetMapping("values")
    public Resp values(){
        return Resp.of(Config.configMap());
    }

    @PostMapping("save")
    @Transactional
    public Resp save(@RequestBody Map<String,String> configs){
        Set<String> changeKeys=new HashSet<>();
        for (Map.Entry<String,String> entry:configs.entrySet()){
           if(Config.saveConfig(entry.getKey(),entry.getValue())){
               changeKeys.add(entry.getKey());
           }
        }
        if(changeKeys.size()>0){
            ConfigChangeEvent event=new ConfigChangeEvent(this,changeKeys);
            context.publishEvent(event);
        }

        return Resp.ok();
    }
//    @PostMapping("upload")
//    public Resp<String> upload(MultipartFile file){
//        return Resp.ok();
//    }
//    @PostMapping("remove")
//    public Resp<String> remove(String path){
//        return Resp.ok();
//    }
//    @GetMapping("file/{path}")
//    public ResponseEntity file(){
//        return null;
//    }

}
